package com.cfets.annualAssessment.backgroundController;

import com.cfets.annualAssessment.entity.*;
import com.cfets.annualAssessment.service.*;
import com.cfets.annualAssessment.util.*;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * Created by ShenYiChou on 2016/12/23.
 */
@Controller
@RequestMapping("/admin/annual")
public class AnnualController {
    @Autowired
    private RedisRunner redisRunner;
    @Autowired
    private AnnualInformService annualInformService;
    @Autowired
    private AnnualParaService annualParaService;
    @Autowired
    private GroupService groupService;
    @Autowired
    private SchoolService schoolService;
    @Autowired
    private SMSBlackService smsBlackService;
    @Autowired
    private ParameterService parameterService;

    @RequestMapping("/index")
    public String index(Model model){
        return "annualInform";
    }

//    @CrossOrigin
    @RequestMapping(value = "/Get",method = RequestMethod.POST)
    public ResponseEntity<?> annualInformList(AnnualInform annualInform){
        List<AnnualInform> annualInformList = annualInformService.getAnnualInformPage(annualInform);
        TableContainer tableContainer = new TableContainer();
        tableContainer.setAaData(annualInformList);
        tableContainer.setiTotalDisplayRecords(annualInform.getTotalCount());
        tableContainer.setiTotalRecords(annualInform.getTotalCount());
        return new ResponseEntity<>(tableContainer, HttpStatus.OK);
    }
    //批量与年检初始化
    @RequestMapping(value = "/AnnualInformMore",method = RequestMethod.POST)
    public ResponseEntity<?> annualMoreProcess (annualInformMore annualInformMore){
        String[] item;
        boolean flag = true;
        if (annualInformMore.getIds() != null){
            item = annualInformMore.getIds().split(",");
            //批量删除
            if (annualInformMore.getProcess()==1) {
                for (int i = 0; i < item.length; i++) {
                    flag = this.annualInformService.deleteAnnualInformById(Integer.parseInt(item[i]));
                    if (flag == false) {
                        return new ResponseEntity<>(flag, HttpStatus.OK);
                    }
                }
            }
            //批量通过pass
            else if (annualInformMore.getProcess()==2) {
                for (int i = 0; i < item.length; i++) {
                    AnnualInform annualInform = new AnnualInform();
                    annualInform.setId(Integer.parseInt(item[i]));
                    annualInform.setAnnual_stat(3);
                    annualInform.setCa_stat(1);
                    flag = this.annualInformService.updateAnnualInform(annualInform);
                    if (flag == false) {
                        return new ResponseEntity<>(flag, HttpStatus.OK);
                    }
                }
            }
            //批量不通过nopass
            else if (annualInformMore.getProcess()==3) {
                for (int i = 0; i < item.length; i++) {
                    AnnualInform annualInform = new AnnualInform();
                    annualInform.setId(Integer.parseInt(item[i]));
                    annualInform.setAnnual_stat(4);
                    annualInform.setCa_stat(annualInformService.CaCancelOrNot(Integer.parseInt(item[i])));
                    flag = this.annualInformService.updateAnnualInform(annualInform);
                    if (flag == false) {
                        return new ResponseEntity<>(flag, HttpStatus.OK);
                    }
                }
            }
        }else{
            //年检初始化
            if (annualInformMore.getProcess()==4) {
                annualInformService.annualInitial();
            }
            else if (annualInformMore.getProcess()==5){
                annualInformService.annualEnd();
            }
        }
        return new ResponseEntity<>(flag, HttpStatus.OK);
    }

    //工作经历get
    @RequestMapping(value = "/WorkExp",method = RequestMethod.GET)
    public ResponseEntity<?> workExpList(String id_num){
        List<WorkExp> workExpList = annualInformService.getWorkExpsByCID(id_num);
        return new ResponseEntity<>(workExpList, HttpStatus.OK);
    }
    //工作经历post
    @RequestMapping(value = "/newWorkExp",method = RequestMethod.POST)
    public ResponseEntity<?> workExpListUpdate(WorkExpList workExpList) {
        boolean flag = true;
        flag = this.updateWorkExp(workExpList.getWorkExpList());
        return new ResponseEntity<>(flag, HttpStatus.OK);
    }

    @PostMapping
    public ResponseEntity<?> AnnualUpdate(@Valid AnnualInform annualInform, BindingResult result) {
        if (result.hasErrors()) {
            return new ResponseEntity<>(result.getAllErrors(), HttpStatus.OK);
        }
        boolean flag = false;
        if(annualInform.getId()!=null && annualInform.getId()!=0){
            flag = this.annualInformService.updateAnnualInform(annualInform);
        }
        return new ResponseEntity<>(flag, HttpStatus.OK);
    }
    //单个删除
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteAnnualInform(@PathVariable("id") int id){
        boolean flag = this.annualInformService.deleteAnnualInformById(id);
        return new ResponseEntity<>(flag, HttpStatus.OK);
    }

    @RequestMapping(value = "/import",method = RequestMethod.POST)
    public ResponseEntity<?> importExcel(MultipartFile annualFile){
        try {
            Workbook xwb = WorkbookFactory.create(annualFile.getInputStream());
            Sheet sheet = xwb.getSheetAt(0);
            Row row;
            for (int i = sheet.getFirstRowNum(); i < sheet.getPhysicalNumberOfRows(); i++) {
                if(i==0){
                    continue;
                }
                boolean flag = false;
                row = sheet.getRow(i);
                AnnualInform annualInform = new AnnualInform();
                InitialFronSelector initialFronSelector = this.parameterService.getInitialFronSelector();
                annualInform.setDept_typeList(initialFronSelector.getDept_typeList());
                annualInform.setDuty_typeList(initialFronSelector.getDuty_typeList());
                annualInform.setPos_typeList(initialFronSelector.getPos_typeList());
                List<WorkExp> workExpList = new ArrayList<>();
                annualInform.setId_num(row.getCell(4).toString());//must
                List<AnnualInform> annualInformList = this.annualInformService.getAnnualInformPage(annualInform);
                if(!annualInformList.isEmpty()){
                    annualInform = annualInformList.get(0);
                }

                annualInform.setCa_num(row.getCell(1).toString());//must
                annualInform.setName(row.getCell(2).toString());//must
                annualInform.impId_type(row.getCell(3).toString());//must
                annualInform.impOrg_type(row.getCell(6).toString());//在后面
                annualInform.setOrg_name(row.getCell(5).toString());
                annualInform.impAnnual_stat(row.getCell(6).toString());//都要转换的估计//must
                annualInform.impBf_annual_stat(row.getCell(9).toString());//没这个数据
                annualInform.impCa_stat(row.getCell(7).toString());//都要转换的估计//must
                annualInform.setQq(row.getCell(11).toString());
                annualInform.impDept_type(row.getCell(12).toString());//都要转换的估计
                annualInform.setDept(row.getCell(13).toString());
                annualInform.impDuty_type(row.getCell(14).toString());//都要转换的估计
                annualInform.setDuty(row.getCell(15).toString());
                annualInform.impPos_type(row.getCell(16).toString());//都要转换的估计
                annualInform.setDeal_type(row.getCell(17).toString());//都要转换的估计
                annualInform.setMobile(row.getCell(18).toString());
                annualInform.setPhone(row.getCell(19).toString());
                annualInform.setCred_record(row.getCell(20).toString());
                annualInform.setOrg_addr(row.getCell(21).toString());
                annualInform.setPostcode(row.getCell(22).toString());
                annualInform.setFax(row.getCell(23).toString());
                annualInform.setE_mail(row.getCell(24).toString());
                annualInform.impSex(row.getCell(25).toString());//都要转换的估计
                annualInform.setBirth_date(row.getCell(26).toString());
                annualInform.setHighest_edu(row.getCell(27).toString());
                annualInform.setDegree(row.getCell(28).toString());
                annualInform.setHighest_sch(row.getCell(29).toString());
                annualInform.setMajor(row.getCell(30).toString());
                annualInform.setGraduate_date(row.getCell(31).toString());
                annualInform.setPosition(row.getCell(32).toString());
                for (int j = 33; j < sheet.getRow(i).getPhysicalNumberOfCells(); j++){
                    if(row.getCell(33).toString().equals("")) break;
                    WorkExp workExp = new WorkExp();
                    workExp.setId_num(row.getCell(5).toString());
                    switch ((j-32)%6){
                        case 1:workExp.setStart_date(row.getCell(j).toString());
                        case 2:workExp.setFinal_date(row.getCell(j).toString());
                        case 3:workExp.setOrg_fullname(row.getCell(j).toString());
                        case 4:workExp.setDepartment(row.getCell(j).toString());
                        case 5:workExp.setBusiness(row.getCell(j).toString());
                        case 6:workExp.setJob(row.getCell(j).toString());workExpList.add(workExp);
                    }
                }
                this.updateWorkExp(workExpList);
                if(annualInform.getId()!=null && annualInform.getId()!=0){
                    this.annualInformService.updateAnnualInform(annualInform);
                } else {
                    this.annualInformService.newAnnualInform(annualInform);
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>(false, HttpStatus.OK);
        }
        return new ResponseEntity<>(true, HttpStatus.OK);
    }

//    @RequestMapping(value = "/restful/permit",method = RequestMethod.POST)//前台登录分发token
//    public ResponseEntity<?> annualPermit(AnnualInform annualInform){
//        if(annualInform.getCa_num()==null||annualInform.getName()==null||
//                annualInform.getId_num()==null) {
//            return new ResponseEntity<>(false, HttpStatus.OK);
//        }
//        List<AnnualInform> annualInformList = annualInformService.getAnnualInformRest(annualInform);
//        if (annualInformList.isEmpty()||annualInformList.size()>1){
//            return new ResponseEntity<>(false, HttpStatus.OK);
//        }
//        String tokenValue = UUID.randomUUID().toString();
//        //是否年检 start
//        if (this.annualParaService.isDuringAnnual().isEmpty()){
//            redisRunner.cacheAddUpdate(Constant.REDIS_FRONT_END_PERMISSION_DB,
//                    tokenValue, "1", Constant.REDIS_FRONT_END_PERMISSION_EXPIRY);
//            tokenValue += "1";
//        }else{
//            redisRunner.cacheAddUpdate(Constant.REDIS_FRONT_END_PERMISSION_DB,
//                    tokenValue, "0", Constant.REDIS_FRONT_END_PERMISSION_EXPIRY);
//            tokenValue += "0";
//        }
//        //是否年检 end
//        return new ResponseEntity<>(tokenValue, HttpStatus.OK);
//    }

    @RequestMapping(value = "/restful",method = RequestMethod.POST)//前台单组数据获取
    public ResponseEntity<?> annualRestList(AnnualInform annualInform){
        if(annualInform.getCa_num()==null||annualInform.getName()==null||
                annualInform.getId_num()==null) {
            return new ResponseEntity<>(false, HttpStatus.OK);
        }
        List<AnnualInform> annualInformList = annualInformService.getAnnualInformRest(annualInform);
        if (annualInformList.isEmpty()||annualInformList.size()>1){
            return new ResponseEntity<>(false, HttpStatus.OK);
        }
        for(AnnualInform item:annualInformList) {
            item.setWorkExpList(annualInformService.getWorkExpsByCID(item.getId_num()));
            item.setAnnualHistoryList(annualInformService.getAnnualHistory(item.getCa_num()));
            item.setHonorList(annualInformService.getHonors(item.getId_num()));
        }
        return new ResponseEntity<>(annualInformList.get(0), HttpStatus.OK);
    }
    @RequestMapping(value = "/restful/updateAnnual",method = RequestMethod.POST)
    public ResponseEntity<?> updateAllAnnual(@Valid AnnualInform annualInform, BindingResult result){
        if (result.hasErrors()) {
            return new ResponseEntity<>(result.getAllErrors(), HttpStatus.OK);
        }
        boolean flag = true;
        boolean flag1 = true;
        if (this.annualInformService.setAnnualRestUpdateLog(annualInform)) {
            if (annualInform.getId() != null && annualInform.getId() != 0) {
                flag = this.annualInformService.updateAnnualInform(annualInform);
                if (annualInform.getWorkExpList() != null) {
                    flag1 = this.updateWorkExp(annualInform.getWorkExpList());
                }
            }
        }
        if(!flag||!flag1){
            return new ResponseEntity<>(false, HttpStatus.OK);
        }
        return new ResponseEntity<>(true, HttpStatus.OK);
    }

    @RequestMapping("/exportEmail")
    public String exportEmail(HttpServletResponse response){
        List<AnnualInform> mailList = this.annualInformService.getEmail();
        TextUtil.writeEmailToTxt(response, mailList);
        return null;
    }

    @RequestMapping("/exportAnnual")
    public String exportAnnual(HttpServletResponse response){
        AnnualInform annualInform = new AnnualInform();
        List<AnnualInform> annualInformList = this.annualInformService.getAnnualInformRest(annualInform);
        List<AnnualInformComplete> annualInformCompleteList = new ArrayList<>();
        InitialFronSelector initialFronSelector = this.parameterService.getInitialFronSelector();
        annualInform.setDept_typeList(initialFronSelector.getDept_typeList());
        annualInform.setDuty_typeList(initialFronSelector.getDuty_typeList());
        annualInform.setPos_typeList(initialFronSelector.getPos_typeList());
        for(AnnualInform item:annualInformList){
            AnnualInformComplete annualInformComplete = new AnnualInformComplete();
            annualInformComplete.setWechat_name(item.getWechat_name());
            annualInformComplete.setCa_num(item.getCa_num());
            annualInformComplete.setName(item.getName());//must
            annualInformComplete.expId_type(item.getId_type());//must都要转换的估计
            annualInformComplete.setId_num(item.getId_num());//must
            annualInformComplete.expOrg_type(item.getOrg_type());//都要转换的估计
            annualInformComplete.setOrg_name(item.getOrg_name());
            annualInformComplete.expAnnual_stat(item.getAnnual_stat());//都要转换的估计//must
            annualInformComplete.expBf_annual_stat(item.getBf_annual_stat());//都要转换的估计
            annualInformComplete.expCa_stat(item.getCa_stat());//都要转换的估计//must
            annualInformComplete.setQq(item.getQq());
            annualInformComplete.expDept_type(item.getDept_type(),annualInform.getDept_typeList());//都要转换的估计
            annualInformComplete.setDept(item.getDept());
            annualInformComplete.expDuty_type(item.getDuty_type(),annualInform.getDuty_typeList());//都要转换的估计
            annualInformComplete.setDuty(item.getDuty());
            annualInformComplete.expPos_type(item.getPos_type(),annualInform.getPos_typeList());//都要转换的估计
            annualInformComplete.setDeal_type(item.getDeal_type());//都要转换的估计
            annualInformComplete.setMobile(item.getMobile());
            annualInformComplete.setPhone(item.getPhone());
            annualInformComplete.setCred_record(item.getCred_record());
            annualInformComplete.setOrg_addr(item.getOrg_addr());
            annualInformComplete.setPostcode(item.getPostcode());
            annualInformComplete.setFax(item.getFax());
            annualInformComplete.setE_mail(item.getE_mail());
            annualInformComplete.expSex(item.getSex());//都要转换的估计
            annualInformComplete.setBirth_date(item.getBirth_date());
            annualInformComplete.setHighest_edu(item.getHighest_edu());
            annualInformComplete.setDegree(item.getDegree());
            annualInformComplete.setHighest_sch(item.getHighest_sch());
            annualInformComplete.setMajor(item.getMajor());
            annualInformComplete.setGraduate_date(item.getGraduate_date());
            annualInformComplete.setPosition(item.getPosition());
            annualInformComplete.setWorkExpList(this.annualInformService.getWorkExpsByCID(item.getId_num()));
            annualInformCompleteList.add(annualInformComplete);
        }
        ExcelUtil.exportAnnualExcel("年检全量数据",
                new String[]{"NO.","wechat_name","ca_num","name","id_type","id_num","org_type","org_name","annual_stat",
                        "bf_annual_stat","ca_stat","qq","dept_type","dept","duty_type","duty","pos_type","deal_type",
                        "mobile","phone","cred_record","org_addr","postcode","fax","e_mail","sex","birth_date",
                        "highest_edu","degree","highest_sch","major","graduate_date","position"},
                new String[]{"","wechat_name","ca_num","name","id_type","id_num","org_type","org_name","annual_stat",
                        "bf_annual_stat","ca_stat","qq","dept_type","dept","duty_type","duty","pos_type","deal_type",
                        "mobile","phone","cred_record","org_addr","postcode","fax","e_mail","sex","birth_date",
                        "highest_edu","degree","highest_sch","major","graduate_date","position"},
                new String[]{"start_date","final_date","business","org_fullname","department","job"},
                annualInformCompleteList, response );
        return null;
    }

    public boolean updateWorkExp(List<WorkExp> workExps){
        boolean flag1 = true;
        if(!workExps.isEmpty()){
            List<WorkExp> workExps1 = annualInformService.getWorkExpsByCID(workExps.get(0).getId_num());
            if(!workExps1.isEmpty()){
                for(WorkExp item:workExps1){
                    flag1 = this.annualInformService.deleteWorkExpById(item.getId());
                    if (!flag1) {
                        return false;
                    }
                }
            }
            for(WorkExp item:workExps){
                flag1 = this.annualInformService.newWorkExp(item);
                if (!flag1) {
                    return false;
                }
            }
        }
        return true;
    }

    @RequestMapping(value = "/restful/sendMail",method = RequestMethod.POST)
    public ResponseEntity<?> sendMail(SendMail sendMail) throws Exception {//SendMail
        MailUtil.SendMail(sendMail);
        return new ResponseEntity<>(true, HttpStatus.OK);
    }

    @RequestMapping(value = "/restful/sendSMS",method = RequestMethod.POST)
    public ResponseEntity<?> sendSMS(SendSMS sendSMS){//SendSMS
        ArrayList<String> phoneNumbers = new ArrayList<>();
        Group group = new Group();
        group.setGroup_name(sendSMS.getSendGrp());
        SMSBlack smsBlack = new SMSBlack();
        List<GroupMember> groupMemberList = this.groupService.GroupMemberList(group);
        for(GroupMember it:groupMemberList){
            String mobile = it.getMobile();
            if(!mobile.isEmpty()){
                smsBlack.setMobile(mobile);
                if(this.smsBlackService.getSMSBlack(smsBlack).isEmpty()){
                    phoneNumbers.add(mobile);
                }
            }
        }
        boolean flag = SmsSDKDemo.SmsMultiUtil(phoneNumbers,sendSMS.getTempNo()
        ,sendSMS.getSMSPara1(),sendSMS.getSMSPara2(),sendSMS.getSMSPara3(),sendSMS.getSMSPara4(),sendSMS.getSMSPara5());//参数1~5 模板号 内容 电话号码 群组
        return new ResponseEntity<>(flag, HttpStatus.OK);
    }
    @RequestMapping(value = "/restful/ResTemp",method = RequestMethod.POST)
    public ResponseEntity<?> ResTempSMS(String ResTemp, HttpServletResponse response){

        return null;
    }

    @ModelAttribute("schools")//可以改一改
    public List<String> getSchools(){
        List<School> schoolList = schoolService.getSchool();
        List<String> schools = new ArrayList<>();
        for(School item:schoolList){
            schools.add(item.getSchool_name());
        }
        return schools;
    }
}
